package com.dctp.ems.controller;

import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.dctp.ems.config.OpsLog;
import com.dctp.ems.interceptor.OpsLogInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.ArrayList;
import java.util.List;

/**
 * USDT充值网络配置表管理
 * basePath: /rechargeConfig
 */
@Path("/rechargeConfig")
public class RechargeConfigController extends BaseController {

    // 分页查询
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        String network = getPara("network", "");
        String address = getPara("address", "");
        String isDefault = getPara("is_default", "");
        String status = getPara("status", "");

        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> ps = new ArrayList<>();
        if (StrKit.notBlank(network))  { where.append("AND network LIKE ? ");  ps.add('%'+network+'%'); }
        if (StrKit.notBlank(address))  { where.append("AND address LIKE ? ");  ps.add('%'+address+'%'); }
        if (StrKit.notBlank(isDefault)) { where.append("AND is_default = ? "); ps.add(isDefault); }
        if (StrKit.notBlank(status)) { where.append("AND status = ? "); ps.add(status); }

        var p = Db.paginate(page, pageSize,
                "SELECT * ",
                "FROM dctp_recharge_config "+where+" ORDER BY display_order ASC",
                ps.toArray());
        renderJson(JsonResult.successWithData(
            new PageResult<>(p.getList(), p.getTotalRow(), pageSize, page)
        ));
    }

    // 新增
    @Before({Tx.class, OpsLogInterceptor.class})
    @OpsLog(module = "收款地址",
            action = "新增收款地址",
            addKey = "network",
            addLabel = "充值网络")
    public void add() {
        Record body = jsonBody();
        if (StrKit.isBlank(body.getStr("network")) || StrKit.isBlank(body.getStr("address"))) {
            renderJson(JsonResult.failWithMessage("network 与 address 均不能为空"));
            return;
        }
        // 保证 is_default=1 只能有一条
        if (body.getInt("is_default") != null && body.getInt("is_default") == 1) {
            Db.update("UPDATE dctp_recharge_config SET is_default=0 WHERE is_default=1");
        }
        body.set("create_time", DateUtil.now());
        if (!Db.save("dctp_recharge_config", body))
            throw new RuntimeException("新增充值配置失败");
        renderJson(JsonResult.success());
    }

    // 修改
    @Before({Tx.class, OpsLogInterceptor.class})
    @OpsLog(module = "收款地址",
            action = "修改收款地址",
            table = "dctp_recharge_config",
            fields = {"network","address","qr_code","status"})
    public void update() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        Record body = jsonBody();
        if (body.getColumns().isEmpty()) {
            renderJson(JsonResult.failWithMessage("无有效字段"));
            return;
        }
        // 保证 is_default=1 只能有一条
        if (body.getInt("is_default") != null && body.getInt("is_default") == 1) {
            Db.update("UPDATE dctp_recharge_config SET is_default=0 WHERE is_default=1 AND id<>?", id);
        }
        body.set("id", id)
            .set("update_time", DateUtil.now());
        if (!Db.update("dctp_recharge_config", body))
            throw new RuntimeException("充值配置不存在或已删除");
        renderJson(JsonResult.success());
    }

    // 删除
    @Before(Tx.class)
    public void delete() {
        Long id = getParaToLong(0);
        if (id == null) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        int n = Db.update("DELETE FROM dctp_recharge_config WHERE id=?", id);
        if (n == 0) throw new RuntimeException("充值配置不存在或已删除");
        renderJson(JsonResult.success());
    }

    // 启用的充值网络列表
    public void all() {
        List<Record> rows = Db.find("SELECT id,network,address,qr_code,is_default FROM dctp_recharge_config WHERE status=1");
        renderJson(JsonResult.successWithData(rows));
    }
}
